package com.gjm.tool.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.style.StyleUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {

    /**
     * 读取excel
     *
     * @param filePath  excel文件地址
     * @param sheetNum  第几个sheet 从0开始
     * @param indexList 读取哪些列，从0开始
     * @return
     */
    public static List<List<String>> readExcel(String filePath, int sheetNum, List<Integer> indexList) {
        List<List<String>> fieldList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(indexList)) {
            ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(filePath);
            // 读取指定sheet页面，0表示第一个sheet
            List<List<Object>> sheetList = reader.read(sheetNum);
            // 关闭读取器，释放资源
            reader.close();
            for (List<Object> objects : sheetList) {
                List<String> list = new ArrayList<>();
                for (Integer index : indexList) {
                    list.add(getFieldValue(objects, index));
                }
                fieldList.add(list);
            }
        }
        return fieldList;
    }

    /**
     * 写入excel
     *
     * @param filePath
     * @param rows
     */
    public static void writeExcel(String filePath, List<List<String>> rows, List<Integer> removeList) {
        // 创建一个ExcelWriter对象，用于写入数据
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(filePath);
        // 写入数据
        writer.write(rows);
        //设置颜色
        //为数据表格填充样式
        Workbook workbook = writer.getWorkbook();
        //创建默认样式
        CellStyle cellStyle = StyleUtil.createDefaultCellStyle(workbook);
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        for (Integer rowIndex : removeList) {
            for (int i = 0; i < 21; i++) {
                writeExcel(writer,cellStyle, i, rowIndex);
            }
        }
        // 写入数据到文件并关闭writer
        writer.close();
    }

    /**
     * 填充颜色
     *
     * @param writer
     * @param columnNum
     * @param rowNum
     */
    public static void writeExcel(ExcelWriter writer,CellStyle cellStyle, int columnNum, int rowNum) {
        try {
            writer.getCell(columnNum, rowNum).setCellStyle(cellStyle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFieldValue(List<Object> list,Integer index) {
        String result = "";
        if (CollectionUtil.isNotEmpty( list) && list.size() > index){
            result = String.valueOf(list.get(index));
        }
        return result;
    }
}
